<template>
  <el-dialog title="分配角色" :visible="visibleDialog" @close="closeFn">
    <!-- v-model:绑定的值的类型为数组的变量，变量和label双向绑定
    label：渲染复选框后面的内容 -->
    <el-checkbox-group v-model="checkList">
      <el-checkbox
        v-for="item in roleList"
        :key="item.id"
        :label="item.id"
      >{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button size="small" type="primary" @click="confrimFn">确定</el-button>
      <el-button size="small" @click="closeFn">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleList } from '@/api/setting'
import { getUserDetailByid, assignRoles } from '@/api/employees'
export default {
  props: {
    visibleDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      checkList: [],
      roleList: [],
      userId: ''
    }
  },
  // 保存角色列表
  async created() {
    const res = await getRoleList({
      page: 1,
      pagesize: 1000
    })
    this.roleList = res.rows
  },
  methods: {
    async getUserDetail(id) {
      const res = await getUserDetailByid(id)
      //   保存默认的角色列表，并实现回显，把角色列表赋值给checklist，从而实现回显
      //   添加短路运算，防止res.roleIds不正确导致报错问题
      this.checkList = res.roleIds || []
      //   保存员工id，并在确定的事件处理函数中调用分配权限接口
      this.userId = id
    },
    async confrimFn() {
      // 确定分配权限
      await assignRoles({
        id: this.userId,
        roleIds: this.checkList
      })
      this.closeFn()
    },
    // 关闭弹窗
    closeFn() {
      this.$emit('update:visibleDialog', false)
      this.checkList = []
    }
  }
}
</script>
<style scoped>

</style>
